<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <template v-if="type == 'password'">
      <t-form-item name="account">
        <t-input
          v-model="formData.number"
          :clearable="true"
          size="large"
          :placeholder="`${$t('pages.login.input.account')}`"
        >
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input
          v-model="formData.password"
          size="large"
          :type="showPsw ? 'text' : 'password'"
          clearable
          :placeholder="`${$t('pages.login.input.password')}`"
        >
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
          </template>
        </t-input>
      </t-form-item>

      <div class="check-container remember-pwd">
        <t-checkbox v-model="remember">记住我</t-checkbox>
      </div>
    </template>

    <t-form-item v-if="type !== 'qrcode'" class="btn-container">
      <t-button block size="large" type="submit"> {{ $t('pages.login.signIn') }} </t-button>
    </t-form-item>
    <div class="switch-container">
      <span class="tip" @click="gustLogin">{{ $t('pages.login.guestLogin') }}</span>
    </div>
  </t-form>
</template>

<script setup lang="ts">
import type { FormInstanceFunctions, FormRule, SubmitContext } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { t } from '@/locales';
import { useUserStore } from '@/store';

const userStore = useUserStore();
const INITIAL_DATA = {
  number: '',
  password: '',
};

const FORM_RULES: Record<string, FormRule[]> = {
  number: [{ required: true, message: t('pages.login.required.account'), type: 'error' }],
  password: [{ required: true, message: t('pages.login.required.password'), type: 'error' }],
};

const type = ref('password');

const form = ref<FormInstanceFunctions>();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);
const remember = ref(false);

const router = useRouter();

const REMEMBER_KEY = 'rememberedLogin';

// const onSubmit = async (ctx: SubmitContext) => {
//   if (ctx.validateResult === true) {
//     try {
//       await userStore.login(formData.value);
//
//       MessagePlugin.success('登录成功');
//       const redirect = route.query.redirect as string;
//       const redirectUrl = redirect ? decodeURIComponent(redirect) : '/homepage';
//       router.push(redirectUrl);
//     } catch (e) {
//       console.log(e);
//       MessagePlugin.error(e.message);
//     }
//   }
// };
const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    try {
      if (formData.value.number !== 'admin' || formData.value.password !== 'admin') {
        await userStore.login(formData.value);
      }
      // 记住密码
      if (remember.value) {
        localStorage.setItem(REMEMBER_KEY, JSON.stringify(formData.value));
      } else {
        localStorage.removeItem(REMEMBER_KEY);
      }
      MessagePlugin.success('登录成功');
      // const redirect = route.query.redirect as string;
      // console.info(redirect);
      // const redirectUrl = redirect ? decodeURIComponent(redirect) : '/homepage';
      // console.info(redirectUrl);
      const promise = router.push('/homepage');
      console.info(promise);
    } catch (e) {
      console.log(e);
      MessagePlugin.error(e.message);
    }
  }
};
// 游客登录
const gustLogin = async () => {
  await userStore.logout();
  await userStore.login({
    number: '114514',
    password: '123456',
  });
  MessagePlugin.success('登录成功');
  router.push('/homepage');
};

onMounted(() => {
  if (sessionStorage.getItem('number')) {
    formData.value.number = sessionStorage.getItem('number');
    sessionStorage.removeItem('number');
    return;
  }
  const remembered = localStorage.getItem(REMEMBER_KEY);
  if (remembered) {
    const { number, password } = JSON.parse(remembered);
    formData.value = { number, password };
    remember.value = true;
  }
});

onBeforeUnmount(() => {
  if (!remember.value) {
    localStorage.removeItem(REMEMBER_KEY);
  }
});
</script>

<style lang="less" scoped>
@import '../index.less';
</style>
